import 'package:better_player/better_player.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:crypto/crypto.dart';

// 视频类型枚举（定义在类外部）
enum VideoType { encryptedHLS, mp4 }

class EncryptedHlsPage extends StatefulWidget {
  @override
  _EncryptedHlsPageState createState() => _EncryptedHlsPageState();
}

class _EncryptedHlsPageState extends State<EncryptedHlsPage> {
  late BetterPlayerController _betterPlayerController;
  final TextEditingController _urlController = TextEditingController();
  final TextEditingController _keyServerController = TextEditingController();

  VideoType _selectedVideoType = VideoType.encryptedHLS; // 默认选择加密HLS

  // 预设的测试URL（包含加密HLS和MP4）
  final Map<VideoType, List<Map<String, String>>> _presetUrls = {
    // 加密HLS流预设URL
    VideoType.encryptedHLS: [
      {
        'name': 'CDN单密钥加密HLS测试',
        'url': 'https://video.yangcongmanhua.com/hls/test_video_11/stream.m3u8',
        'keyServer': 'http://192.168.166.238:8080/key/test_video_11',
        'description': '所有TS分片共享一个AES-128密钥，优化的单密钥方案'
      },
    ],
    // MP4视频预设URL
    VideoType.mp4: [
      {
        'name': 'CDN点播MP4测试',
        'url': 'https://video.yangcongmanhua.com/lixu_test/hls/input.mp4',
        'keyServer': '', // MP4不需要密钥服务器
        'description': '直接播放MP4视频文件'
      },
    ],
  };

  @override
  void initState() {
    super.initState();
    _initializePlayer();
    _loadDefaultUrls(); // 加载默认URL配置
  }

  /// 根据当前选择的视频类型加载默认URL
  void _loadDefaultUrls() {
    final currentPresets = _presetUrls[_selectedVideoType] ?? [];
    if (currentPresets.isNotEmpty) {
      setState(() {
        _urlController.text = currentPresets[0]['url']!;
        _keyServerController.text = currentPresets[0]['keyServer']!;
      });
    }
  }

  void _initializePlayer() {
    BetterPlayerConfiguration betterPlayerConfiguration = BetterPlayerConfiguration(
      aspectRatio: 16 / 9,
      fit: BoxFit.contain,
      autoPlay: true,
      looping: false,
      allowedScreenSleep: false,
      controlsConfiguration: BetterPlayerControlsConfiguration(
        enableOverflowMenu: true,
        enablePlaybackSpeed: true,
        enableMute: true,
        enableFullscreen: true,
        showControlsOnInitialize: true,
      ),
    );

    _betterPlayerController = BetterPlayerController(betterPlayerConfiguration);
  }

  /// 根据选择的视频类型加载对应的视频流
  void _loadVideoStream() {
    final String url = _urlController.text.trim();
    final String keyServer = _keyServerController.text.trim();

    // 验证URL输入
    if (url.isEmpty) {
      _showSnackBar('请输入视频URL', isError: true);
      return;
    }

    // 根据视频类型创建不同的数据源
    BetterPlayerDataSource dataSource;

    switch (_selectedVideoType) {
      case VideoType.encryptedHLS:
        // 处理加密HLS流
        dataSource = _createEncryptedHLSDataSource(url, keyServer);
        _showSnackBar('开始加载加密HLS流...');
        break;

      case VideoType.mp4:
        // 处理MP4视频
        dataSource = _createMP4DataSource(url);
        _showSnackBar('开始加载MP4视频...');
        break;
    }

    // 设置数据源到播放器
    _betterPlayerController.setupDataSource(dataSource);
  }

  /// 创建加密HLS数据源
  BetterPlayerDataSource _createEncryptedHLSDataSource(String url, String keyServer) {
    if (keyServer.isNotEmpty) {
      // 生成签名（与密钥服务器对齐的算法）
      final signature = _generateSignature(url, keyServer);

      // 使用Token DRM配置（支持多密钥加密）
      return BetterPlayerDataSource(
        BetterPlayerDataSourceType.network,
        url,
        videoFormat: BetterPlayerVideoFormat.hls,
        drmConfiguration: BetterPlayerDrmConfiguration(
          drmType: BetterPlayerDrmType.token,
          token: "KeyServer=$keyServer", // 传递密钥服务器地址
        ),
        headers: {
          'User-Agent': 'BetterPlayer-Flutter',
          'X-Key-Server': keyServer, // 自定义Header传递密钥服务器信息
          'X-Original-URL': url, // 原始视频URL用于签名验证
          'X-Signature': signature, // 签名验证
        },
      );
    } else {
      // 普通HLS流（密钥内嵌在m3u8中）
      return BetterPlayerDataSource(
        BetterPlayerDataSourceType.network,
        url,
        videoFormat: BetterPlayerVideoFormat.hls,
      );
    }
  }

  /// 生成签名（与密钥服务器对齐的算法）
  String _generateSignature(String url, String keyServer) {
    // 使用与密钥服务器相同的算法：HMAC-SHA256
    // 密钥需要与密钥服务器配置的签名密钥一致
    const secretKey = 'a1b2c3d4e5f67890abcdef1234567890abcdef1234567890abcdef1234567890';

    // 组合签名数据：URL + 密钥服务器地址 + 视频ID
    // 从URL中提取视频ID（假设URL格式为 .../video_id/stream.m3u8）
    final videoId = _extractVideoIdFromUrl(url);
    final data = '$url|$keyServer|$videoId';

    // 使用HMAC-SHA256生成签名
    final hmac = Hmac(sha256, secretKey.codeUnits);
    final digest = hmac.convert(data.codeUnits);

    return digest.toString();
  }

  /// 从URL中提取视频ID
  String _extractVideoIdFromUrl(String url) {
    try {
      // 假设URL格式为：https://domain.com/path/video_id/stream.m3u8
      final uri = Uri.parse(url);
      final pathSegments = uri.pathSegments;

      // 查找包含stream.m3u8的路径段，然后取前一个段作为video_id
      final m3u8Index = pathSegments.indexWhere((segment) => segment == 'stream.m3u8');
      if (m3u8Index > 0) {
        return pathSegments[m3u8Index - 1];
      }

      // 如果找不到stream.m3u8，尝试从路径中提取最后一个非空段
      final nonEmptySegments = pathSegments.where((segment) => segment.isNotEmpty).toList();
      if (nonEmptySegments.isNotEmpty) {
        return nonEmptySegments.last;
      }
    } catch (e) {
      print('提取视频ID失败: $e');
    }

    // 默认返回'test_video'
    return 'test_video';
  }

  /// 创建MP4数据源
  BetterPlayerDataSource _createMP4DataSource(String url) {
    return BetterPlayerDataSource(
      BetterPlayerDataSourceType.network,
      url,
      videoFormat: BetterPlayerVideoFormat.other, // MP4使用other格式
      headers: {
        'User-Agent': 'BetterPlayer-Flutter',
      },
    );
  }

  /// 使用预设URL填充输入框
  void _usePresetUrl(int index) {
    final currentPresets = _presetUrls[_selectedVideoType] ?? [];
    if (index < currentPresets.length) {
      setState(() {
        _urlController.text = currentPresets[index]['url']!;
        _keyServerController.text = currentPresets[index]['keyServer']!;
      });
    }
  }

  /// 切换视频类型（加密HLS或MP4）
  void _switchVideoType(VideoType newType) {
    if (_selectedVideoType != newType) {
      setState(() {
        _selectedVideoType = newType;
      });
      _loadDefaultUrls(); // 切换类型后加载对应的默认URL
    }
  }

  void _showSnackBar(String message, {bool isError = false}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : Colors.green,
        duration: Duration(seconds: 3),
      ),
    );
  }

  /// 根据当前选择的视频类型返回对应的使用说明
  String _getInstructionText() {
    switch (_selectedVideoType) {
      case VideoType.encryptedHLS:
        return '【加密HLS流播放】\n'
            '1. 使用脚本生成加密HLS流\n'
            '2. 启动密钥服务器\n'
            '3. 选择预设URL或输入自定义URL\n'
            '4. 点击"播放加密HLS流"开始播放\n\n'
            '脚本命令:\n'
            '• 本地测试: ./scripts/run_pipeline.sh -s input.mp4\n'
            '• CDN测试: ./scripts/run_pipeline.sh -s -u input.mp4\n\n'
            '特性: 每个分片使用不同密钥，安全性高';

      case VideoType.mp4:
        return '【MP4视频播放】\n'
            '1. 选择预设MP4 URL或输入自定义URL\n'
            '2. 点击"播放MP4视频"开始播放\n'
            '3. 无需密钥服务器，直接播放\n\n'
            '支持格式:\n'
            '• 标准MP4视频文件\n'
            '• HTTP/HTTPS协议\n'
            '• 自动检测视频编码\n\n'
            '特性: 简单直接，兼容性好';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("视频播放测试"),
        backgroundColor: Colors.blue,
      ),
      body: Column(
        children: [
          // 播放器
          AspectRatio(
            aspectRatio: 16 / 9,
            child: Container(
              color: Colors.black,
              child: BetterPlayer(controller: _betterPlayerController),
            ),
          ),

          // 控制面板
          Expanded(
            child: SingleChildScrollView(
              padding: EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // 视频类型选择器
                  Text(
                    '视频类型选择:',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 8),
                  Row(
                    children: [
                      // 加密HLS选项
                      Expanded(
                        child: RadioListTile<VideoType>(
                          title: Text('加密HLS'),
                          subtitle: Text('多密钥分片加密'),
                          value: VideoType.encryptedHLS,
                          groupValue: _selectedVideoType,
                          onChanged: (VideoType? value) {
                            if (value != null) _switchVideoType(value);
                          },
                        ),
                      ),
                      // MP4选项
                      Expanded(
                        child: RadioListTile<VideoType>(
                          title: Text('MP4视频'),
                          subtitle: Text('直接播放MP4'),
                          value: VideoType.mp4,
                          groupValue: _selectedVideoType,
                          onChanged: (VideoType? value) {
                            if (value != null) _switchVideoType(value);
                          },
                        ),
                      ),
                    ],
                  ),

                  SizedBox(height: 20),

                  // 预设URL选择（根据视频类型动态显示）
                  Text(
                    '预设测试URL:',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 8),
                  ...List.generate(_presetUrls[_selectedVideoType]?.length ?? 0, (index) {
                    final preset = _presetUrls[_selectedVideoType]![index];
                    return Padding(
                      padding: EdgeInsets.only(bottom: 8),
                      child: Card(
                        child: ListTile(
                          title: Text(preset['name']!),
                          subtitle: Text(preset['description']!),
                          trailing: Icon(Icons.play_circle_outline),
                          onTap: () => _usePresetUrl(index),
                        ),
                      ),
                    );
                  }),

                  SizedBox(height: 20),

                  // 视频URL输入（根据类型显示不同提示）
                  Text(
                    _selectedVideoType == VideoType.encryptedHLS ? 'HLS流URL:' : 'MP4视频URL:',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 8),
                  TextField(
                    controller: _urlController,
                    decoration: InputDecoration(
                      hintText: _selectedVideoType == VideoType.encryptedHLS ? '输入HLS流URL (m3u8)' : '输入MP4视频URL',
                      border: OutlineInputBorder(),
                      prefixIcon: Icon(_selectedVideoType == VideoType.encryptedHLS ? Icons.security : Icons.video_file),
                    ),
                    maxLines: 2,
                  ),

                  SizedBox(height: 16),

                  // 密钥服务器URL输入（仅在加密HLS模式下显示）
                  if (_selectedVideoType == VideoType.encryptedHLS) ...[
                    Text(
                      '密钥服务器URL (可选):',
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                    SizedBox(height: 8),
                    TextField(
                      controller: _keyServerController,
                      decoration: InputDecoration(
                        hintText: '输入密钥服务器URL',
                        border: OutlineInputBorder(),
                        prefixIcon: Icon(Icons.vpn_key),
                      ),
                    ),
                    SizedBox(height: 16),
                  ],

                  SizedBox(height: 20),

                  // 播放按钮（根据视频类型显示不同文本）
                  ElevatedButton.icon(
                    onPressed: _loadVideoStream,
                    icon: Icon(Icons.play_arrow),
                    label: Text(_selectedVideoType == VideoType.encryptedHLS ? '播放加密HLS流' : '播放MP4视频'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _selectedVideoType == VideoType.encryptedHLS ? Colors.orange : Colors.green,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(vertical: 12),
                    ),
                  ),

                  SizedBox(height: 20),

                  // 说明文本
                  Container(
                    padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade50,
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.blue.shade200),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '使用说明:',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                            color: Colors.blue.shade800,
                          ),
                        ),
                        SizedBox(height: 8),
                        Text(
                          _getInstructionText(),
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.blue.shade700,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _betterPlayerController.dispose();
    _urlController.dispose();
    _keyServerController.dispose();
    super.dispose();
  }
}
